package com.loren.demo21.task;

import com.loren.demo21.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Objects;

@Slf4j
public class TaskRunnable implements Runnable {

    private final String bean;

    private final String method;

    public TaskRunnable(String bean, String method) {
        this.bean = bean;
        this.method = method;
    }

    @Override
    public void run() {
        try {
            Object target = SpringContextUtils.getBean(this.bean);
            Method method = target.getClass().getDeclaredMethod(this.method);
            ReflectionUtils.makeAccessible(method);
            method.invoke(target);
        } catch (Exception e) {
            log.error("scheduled task execution failed", e);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TaskRunnable that = (TaskRunnable) o;
        return this.bean.equals(that.bean) && this.method.equals(that.method);
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.bean, this.method);
    }
}
